import { queryTrouble, service as axios } from '@vimi/utils-api'
import { excelJsonExport } from '@vimi/utils-tool'
export const exportTable = async ({ columns, table, params, order, filename, adapter }) => {
  const exportTable = columns.filter(item => !item.operations)
  const header = {}
  const headerCellStyles = {}
  const exportColumns = exportTable.map((item, i) => {
    const { prop, label } = item.attrs || {}
    header[prop] = label
    headerCellStyles[`${String.fromCharCode(65 + i)}1`] = { font: { bold: true } }
    return prop
  })

  const { index, size, ...param } = params

  const res = await axios.get(`/api/credit/${table}${queryTrouble(table, param, order)}`, {
    timeout: 0,
  })

  let data = res.data || []
  if (adapter) {
    data = data.map(adapter)
  }

  excelJsonExport({
    columns: exportColumns,
    data: [header, ...data],
    filename,
    styles: {
      border: {
        left: { style: 'thin' },
        top: { style: 'thin' },
        right: { style: 'thin' },
        bottom: { style: 'thin' },
      },
      alignment: {
        vertical: 'center',
        horizontal: 'center',
        wrapText: true,
      },
    },
    cellStyles: {
      ...headerCellStyles,
    },
  })
}
